package com.hjk.common.interceptor;


import com.hjk.common.model.Payload;
import com.hjk.common.model.UserInfo;
import com.hjk.common.utils.threadlocals.UserHolder;
import com.hjk.common.utils.security.JwtUtils;
import com.hjk.common.utils.web.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hjk
 * 2019/11/2 - 15:00
 */
@Slf4j
public class HjkInterceptor implements HandlerInterceptor {

    /**
     * 用户存储token的cookie名
     */
    private static final String COOKIE_NAME = "HJK_TOKEN";

    /**
     * controller 执行前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //获取用户信息
            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
            //解析token
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
            //获取用户信息存入ThreadLocal
            UserHolder.setUser(payload.getId());
            return true;
        } catch (Exception e) {
            log.error("解析用户信息失败 ", e);
            return false;
        }
    }

    /**
     * controller 执行后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 视图解析完成后 执行前
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
